package com.kgc.cgconsumer.Controller;

import com.kgc.cgapi.pojo.CGSQPojo;
import com.kgc.basic.util.ResponseMsg;
import com.kgc.cgconsumer.service.CGConServ;
import com.kgc.cgconsumer.service.CGSQConsumerService;
import com.kgc.cgconsumer.service.CgWorkFlowService;
import com.kgc.cgconsumer.service.ImportExportFeign;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("CGSQ")
public class CGSQController {
    private static Logger logger = LoggerFactory.getLogger(CGSQController.class);

    private String table="cg_acgsq";

    @Autowired
    private CGSQConsumerService cgsqConsumerService;

    @Autowired
    private CGConServ cgConServ;

    @Autowired
    private ImportExportFeign importExportFeign;

    @Autowired
    private CgWorkFlowService cgWorkFlowService;

    @RequestMapping("getCGSQ")
    public ResponseMsg getCGSQ(@RequestParam(name = "code") String code) {
        logger.info("getCGSQ code:{}", code );
        ResponseMsg responseMsg = new ResponseMsg();
        responseMsg = cgsqConsumerService.getCGSQ(code);
        logger.info("getCGSQ code:{} responseMsg:{}",code, responseMsg);
        return responseMsg;
    }

    @RequestMapping("getCGSQInfo")
    public ResponseMsg getCGSQInfo(@RequestParam(name = "code") String code) {
        logger.info("getCGSQInfo code:{}", code );
        ResponseMsg responseMsg = new ResponseMsg();
        responseMsg = cgsqConsumerService.getCGSQInfo(code);
        logger.info("getCGSQInfo code:{} responseMsg:{}",code, responseMsg);
        return responseMsg;
    }


    @RequestMapping("getPage")
    public ResponseMsg getPage(@RequestBody Map<String,Object> map) {
        logger.info("getPage map:{}", map);
        ResponseMsg responseMsg = cgsqConsumerService.getCGSQPage(map);
        logger.info("getPage map:{} responseMsg:{}",map,responseMsg);
        return responseMsg;
    }
    @RequestMapping("getCode")
    public String getCode(){
        logger.info("getCode ");
        String str = cgConServ.getCode(table);
        String code = "CGSQ"+"-" + str;
        logger.info("getCode code:{}",code);
        return code;
    }

    @RequestMapping("addCGSQ")
    public ResponseMsg addCGSQ(@RequestBody Map<String, Object> param) {
        logger.info("addCGSQ cgsq:{}", param);
        ResponseMsg responseMsg = cgsqConsumerService.addCGSQ(param);
        logger.info("add cgsq:{} responseMsg:{}",param,responseMsg);

        Map<String,Object> variables = new HashMap<>();
        variables.put("code",responseMsg.getData());//单据编号
        variables.put("type",param.get("type"));//流程类型
        //创建一个流程实例
        com.kgc.activiti.util.ResponseMsg res = cgWorkFlowService.startProcess(variables);
        if (!"200".equals(res.getCode())){
            responseMsg.setCode(res.getCode());
        }
        return responseMsg;
    }
    @RequestMapping("addCGSQInfo")
    public ResponseMsg addCGSQInfo(@RequestBody Map<String, Object> param) {
        logger.info("addCGSQInfo cgsq:{}", param);
        ResponseMsg responseMsg = cgsqConsumerService.addCGSQInfo(param);
        logger.info("add cgsqInfo:{} responseMsg:{}",param,responseMsg);
        return responseMsg;
    }
    @RequestMapping("delCGSQ")
    public ResponseMsg delCGSQ(@RequestParam(name = "code") String code) {
        logger.info("delCGSQ cgsq:{}", code);
        ResponseMsg responseMsg = new ResponseMsg();
        responseMsg = cgConServ.del(table,code);
        logger.info("del cgsq:{} responseMsg:{}",code,responseMsg);
        return responseMsg;
    }

    @RequestMapping("modiCGSQ")
    public ResponseMsg modiCGSQ(@RequestBody Map<String, Object> param) {
        logger.info("modiCGSQ cgsq:{}", param);
        ResponseMsg responseMsg = cgsqConsumerService.modiCGSQ(param);
        logger.info("modi cgsq:{} responseMsg:{}",param,responseMsg);
        return responseMsg;
    }
    @RequestMapping("modiCGSQInfo")
    public ResponseMsg modiCGSQInfo(@RequestBody Map<String, Object> param) {
        logger.info("modiCGSQInfo cgsq:{}", param);
        ResponseMsg responseMsg = cgsqConsumerService.modiCGSQInfo(param);
        logger.info("modi cgsqInfo:{} responseMsg:{}",param,responseMsg);
        return responseMsg;
    }

    //导入
    @RequestMapping(value = "/import", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseMsg importInfo(@RequestPart("file") MultipartFile file) {
        logger.info("consumer CustomerController importInfo fileName:{}", file.getOriginalFilename());
        return importExportFeign.importInfo(file, "com.kgc.cgapi.pojo.CGSQPojo", "code", "");
    }

    @RequestMapping(value = "/export")
    public void exportSalesInvoices(@RequestBody Map<String, Object> map, HttpServletResponse response) {
        logger.info("consumer SalesInvoiceController exportSalesInvoices params:{}", map);
        try {
            ResponseMsg responseMsg = importExportFeign.exportEntities(map, "com.kgc.cgapi.pojo.CGSQPojo", "create_date desc");
            if ("200".equals(responseMsg.getCode())) {
                String base64Data = (String) responseMsg.getData();
                byte[] exportData = Base64.getDecoder().decode(base64Data);

                //设置响应头
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("UTF-8");
                String filename = URLEncoder.encode("采购申请信息表.xlsx", "UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);

                response.getOutputStream().write(exportData);
            } else {
                logger.error("导出失败, msg: {}", responseMsg.getMsg());
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (IOException e) {
            logger.error("consumer SalesInvoiceController exportSalesInvoices is error", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("/check")
    public  ResponseMsg check(@RequestBody Map<String,Object> map){
        ResponseMsg responseMsg = new ResponseMsg();
        logger.info("SalesOrdersController check params,{}",map.toString());
        Map<String,Object> variables = new HashMap<>();
        variables.put("code",map.get("code"));//单据编号
        variables.put("checkManId",Integer.valueOf((String) map.get("checkManId")));//审批人
        variables.put("checkManName",(String) map.get("checkManName"));//审批人
        variables.put("checkComment",(String) map.get("checkComment"));//审批意见
        variables.put("checkDate",new Date());//审批时间
        variables.put("checkRes",(boolean)map.get("checkRes"));//审批结果
        com.kgc.activiti.util.ResponseMsg msg=  cgWorkFlowService.competeTask(variables);
        responseMsg.setCode(msg.getCode());
        responseMsg.setMsg(msg.getMsg());
        return responseMsg;
    }
}
